@echo off

set PACKAGE=SocketDemo

set SDIR=%~dp0
set JDIR=%SDIR%\%PACKAGE%

java.exe > nul 2>&1
if errorlevel 9009 goto detectJavaHome
javac.exe > nul 2>&1
if errorlevel 9009 goto detectJavaHome

set JAVA_EXE=java.exe
set JAVAC_EXE=javac.exe
goto startBuild

:detectJavaHome
if "%JAVA_HOME%" != "" goto gotJavaHome
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_112

:gotJavaHome
if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
if not exist "%JAVA_HOME%\bin\javac.exe" goto noJavaHome

:gotJavaExe
set JAVA_EXE=%JAVA_HOME%\bin\java.exe
set JAVAC_EXE=%JAVA_HOME%\bin\javac.exe

set ECode=0
:startBuild
pushd "%SDIR%" > nul || exit %ERRORLEVEL%
echo Building ...
"%JAVAC_EXE%" %PACKAGE%\*.java
set ECode=%ERRORLEVEL%
popd > nul || exit %ERRORLEVEL%
if not %ECode% == 0 goto error
echo Done.

:startRun
pushd "%SDIR%" > nul || exit %ERRORLEVEL%
echo Running ...
"%JAVA_EXE%" "%PACKAGE%.App" %*
set ECode=%ERRORLEVEL%
popd > nul || exit %ERRORLEVEL%
if not %ECode% == 0 goto error

goto EOF

:noJavaHome
echo Cannot find Java Environment!
pause
goto EOF

:error
echo Error!
pause
goto EOF

:EOF
